package com.coship.vas.dapg.properties;

import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;


public class SystemOverridenPropertiesFactoryBean extends PropertyPlaceholderConfigurer implements BeanPostProcessor, InitializingBean {
  
  private int systemPropertiesMode = PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_FALLBACK;
 
  private java.util.Properties pros;
  
  public int getSystemPropertiesMode() {
    return systemPropertiesMode;
  }
  
  public void setSystemPropertiesMode(int systemPropertiesMode) {
    this.systemPropertiesMode = systemPropertiesMode;
  }

	/**
	 * 如果properties以system开头，则加上到systemProperties中.
	 */
	
	@SuppressWarnings("unchecked")
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
	throws BeansException{		
		try
		{
			pros = (Properties) super.mergeProperties();
		} catch (IOException e)
		{
			
			e.printStackTrace();
		}
		
		Properties p=new Properties();
		if(systemPropertiesMode==PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE){
			
		  final Properties systemProperties = System.getProperties();
		  for   (Iterator   it   =   pros.keySet().iterator();   it.hasNext();   )   { 
		        String   key   =   (String)   it.next(); 
		        String   value   =  (String) pros.get(key); 
		       if(key.startsWith("system.")){
		    	   p.put(key, value);
		       }
		}
		 systemProperties.putAll(p);
		 System.setProperties(systemProperties);
		}

		return bean;
	}
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
	throws BeansException {
		
		return bean;
	}
	@Override
	  public void afterPropertiesSet() throws Exception {
		pros = mergeProperties();
		}
}